<template>
  <div class="app-container">
    <h2>编辑课程信息</h2>

    <el-form label-width="120px">
      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" />
      </el-form-item>

      <el-form-item label="课程分类">
        <div v-if="courseInfo.subjectLevelOne" class="current-category">
          当前分类：{{ courseInfo.subjectLevelOne }} /
          {{ courseInfo.subjectLevelTwo }}
        </div>
        <el-select
          v-model="courseInfo.subjectParentId"
          @change="subjectLevelOneChanged"
          :loading="loading.subject"
          clearable
        >
          <el-option
            v-for="subject in subjectOneList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>

        <!-- 二级分类 -->
        <el-select
          v-model="courseInfo.subjectId"
          :loading="loading.subject"
          clearable
        >
          <el-option
            v-for="subject in subjectTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="课程讲师">
        <el-select v-model="courseInfo.teacherId" placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="总课时">
        <el-input-number
          :min="0"
          v-model="courseInfo.lessonNum"
          controls-position="right"
          placeholder="请填写课程的总课时数"
        />
      </el-form-item>

      <el-form-item label="课程简介">
        <tinymce :height="300" v-model="courseInfo.description" />
      </el-form-item>

      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleCoverSuccess"
          :before-upload="beforeCoverUpload"
          :action="BASE_API + '/eduoss/fileoss'"
          class="cover-uploader"
        >
          <img :src="courseInfo.cover" class="cover"/>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number
          :min="0"
          v-model="courseInfo.price"
          controls-position="right"
          placeholder="免费课程请设置为0元"
        />
        元
      </el-form-item>

      <el-form-item label="课程状态">
        <el-select
          v-model="courseInfo.status"
          clearable
          placeholder="请选择"
          disabled
        >
          <el-option value="Normal" label="已发布" />
          <el-option value="Draft" label="未发布" />
        </el-select>
        <el-tag type="info" style="margin-left: 10px">
          已发布课程状态不可修改
        </el-tag>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveOrUpdate" :loading="saveLoading"
          >保存</el-button
        >
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import course from "@/api/edu/course";
import Tinymce from "@/components/Tinymce";
import subject from "@/api/edu/subject";

export default {
  components: { Tinymce },
  data() {
    return {
      courseInfo: {
        title: "",
        subjectId: "", //二级分类id
        subjectParentId: "", //一级分类id
        teacherId: "",
        lessonNum: 0,
        description: "",
        cover: "/static/默认封面.jpg",
        price: 0,
        status: "Draft",
      },
      subjectOneList: [], //一级分类
      subjectTwoList: [], //二级分类
      teacherList: [],
      BASE_API: process.env.BASE_API,
      saveLoading: false,
      loading: {
        subject: true,
        teacher: true,
      },
      courseId: null,
    };
  },
  created() {
    if (this.$route.params && this.$route.params.id) {
      this.courseId = this.$route.params.id;
      this.getInfo();
    } else {
      this.initData();
    }
  },
  methods: {
    // 初始化数据
    initData() {
      this.loading.subject = true;
      this.loading.teacher = true;

      Promise.all([subject.getSubjectList(), course.getListTeacher()])
        .then(([subjectRes, teacherRes]) => {
          this.subjectOneList = subjectRes.data.list;
          this.teacherList = teacherRes.data.items;
        })
        .catch((error) => {
          console.error("初始化数据失败:", error);
          this.$message.error("初始化数据失败");
        })
        .finally(() => {
          this.loading.subject = false;
          this.loading.teacher = false;
        });
    },
    getInfo() {
      this.loading.subject = true;
      this.loading.teacher = true;
      course
        .getCourseInfoId(this.courseId)
        .then((response) => {
          //在courseInfo课程基本信息，包含 一级分类id 和 二级分类id
          this.courseInfo = {
            ...response.data.courseInfoVo,
            subjectParentId: response.data.courseInfoVo.subjectParentId || "",
            subjectId: response.data.courseInfoVo.subjectId || "",
            status: response.data.courseInfoVo.status || "Draft",
          };
          return subject.getSubjectList();
        })
        .then((response) => {
          if (!response) return;
          this.subjectOneList = response.data.list;
          if (this.courseInfo.subjectParentId) {
            const oneSubject = this.subjectOneList.find(
              (item) => item.id === this.courseInfo.subjectParentId
            );
            this.subjectTwoList = (oneSubject && oneSubject.children) || [];
          }
          return course.getListTeacher();
        })
        .then((response) => {
          this.teacherList = response.data.items;
        })
        .catch((error) => {
          console.error("获取数据失败:", error);
          this.$message.error("获取课程信息失败");
        })
        .finally(() => {
          this.loading.subject = false;
          this.loading.teacher = false;
        });
    },
    //上传封面成功调用的方法
    handleCoverSuccess(res, file) {
      this.courseInfo.cover = res.data.url;
    },
    //上传之前调用的方法
    beforeCoverUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isJPG) {
        this.$message.error("上传课程封面只能是 JPG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传课程图片大小不能超过 5MB!");
      }
      this.$message.success("上传成功");
      return (isJPG || isPNG) && isLt5M;
    },
    subjectLevelOneChanged(value) {
      //value就是一级分类id值
      //遍历所有的分类，包含一级和二级
      for (var i = 0; i < this.subjectOneList.length; i++) {
        //每个一级分类
        var oneSubject = this.subjectOneList[i];
        //判断：所有一级分类id 和 点击一级分类id是否一样
        if (value === oneSubject.id) {
          //从一级分类获取里面所有的二级分类
          this.subjectTwoList = oneSubject.children;
          //把二级分类id值清空
          this.courseInfo.subjectId = "";
        }
      }
    },
    //查询所有的一级分类
    getOneSubject() {
      subject.getSubjectList().then((response) => {
        this.subjectOneList = response.data.list;
      });
    },
    //查询所有的讲师
    getListTeacher() {
      course.getListTeacher().then((response) => {
        this.teacherList = response.data.items;
      });
    },
    saveOrUpdate() {
      this.saveLoading = true;
      const savePromise = this.courseId
        ? course.updateCourseInfo(this.courseInfo)
        : course.addCourseInfo(this.courseInfo);

      savePromise
        .then(() => {
          this.$message({
            type: "success",
            message: "保存成功!",
          });

          this.$router.push("/course/list");
        })
        .catch(() => {
          this.$message({
            type: "error",
            message: "保存失败!",
          });
        })
        .finally(() => {
          this.saveLoading = false;
        });
    },
    cancel() {
      this.$router.push("/course/list");
    },
  },
};
</script>

<style scoped>
.el-select {
  margin-right: 10px;
}
.el-tag {
  height: 32px;
  line-height: 32px;
}
.current-category {
  margin-bottom: 10px;
  color: #666;
  font-size: 14px;
}

.cover-uploader {
  display: inline-block;
}

.cover-uploader .cover {
  width: 500px;
  height: 250px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}
</style>
